using System.Collections.Generic;
using System.Linq;
using TLDRML.Behaviors;
using TLDRML.Tokens;

namespace TLDRML.Nodes
{
    public class AttributeNode : Node
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public AttributeNode()
        {
        }

        public AttributeNode(string name, string value)
        {
            Name = name;
            Value = value;
        }

        public override IEnumerable<Token> Parse(IEnumerable<Token> tokens)
        {
            if (tokens.First() is NameDeclarationToken)
                tokens = Expect<NameDeclarationToken>(tokens, t => Name = NameDeclarationBehavior.DefaultName());
            else
            {
                tokens = Expect<LiteralToken>(tokens, t => Name = t.Value);
                tokens = Expect<EqualsToken>(tokens, DiscardToken);
            }

            return Parse<ValueNode>(tokens, n => Value = n.Value);
        }

        public bool Equals(AttributeNode other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.Name, Name) && Equals(other.Value, Value);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if ((obj as AttributeNode) == null) return false;
            return Equals((AttributeNode) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return ((Name != null ? Name.GetHashCode() : 0)*397) ^ (Value != null ? Value.GetHashCode() : 0);
            }
        }
    }
}